package com.niodata.md.rdb.crawler;

import com.niodata.md.rdb.model.Column;
import com.niodata.md.rdb.model.Table;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;

/**
 * retrieve column metadata from the target database table.
 */
public class ColumnRetrieval extends AbstractRetrieval {
  @Override
  public List<MetaDataRetrieval> retrieveMetaData() throws Exception {
    String catalogName = this.getCatalog().getName();
    String dbName = this.getCatalog().getDataBase(
        ArrayUtils.subarray(this.getParentPath(), 0, 2)).getName();
    Table table = this.getCatalog().getTable(this.getParentPath());
    String tableName = table.getName();
    //postgresql 使用 catalog+schema获取，其他数据库使用 catalog+databaseName获取
    String db = table.getSchema() == null ? dbName : table.getSchema();
    ResultSet rs = this.getMetaData().getColumns(catalogName, db, tableName, "%");
    List<Column> columns = new ArrayList<>();
    while (rs.next()) {
      Column column = new Column();
      columns.add(column);
      column.setCatalog(catalogName);
      column.setDatabase(dbName);
      column.setSchema(rs.getString("TABLE_SCHEM"));
      column.setColumnSize(rs.getInt("COLUMN_SIZE"));
      column.setName(rs.getString("COLUMN_NAME"));
      column.setDataType(rs.getString("TYPE_NAME"));
      column.setAutoIncrement(rs.getBoolean("IS_AUTOINCREMENT"));
      column.setNullable(rs.getBoolean("IS_NULLABLE"));
      //column.setPrimaryKey(rs.getBoolean("IS_PRIMARY_KEY"));
      //column.setUnique(rs.getBoolean("IS_UNIQUE"));
      column.setRemarks(rs.getString("REMARKS"));
      column.setDefaultValue(rs.getString("COLUMN_DEF"));
    }
    table.setColumns(columns);
    return Collections.EMPTY_LIST;
  }
}
